package com.paco.study.cloud.user.controller;

import com.paco.study.cloud.user.feign.CodeFeignClient;
import com.paco.study.cloud.user.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;

@Slf4j
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private CodeFeignClient codeFeignClient;

//    获取用户信息
    @GetMapping("/info/{token}")
    public String info(@PathVariable String token) {

        return tokenService.searchEmailByCode(token);
    }

//    注册
    @GetMapping("/register/{email}/{password}/{code}")
    public Boolean register(@PathVariable String email,
                            @PathVariable String password,
                            @PathVariable String code,
                            HttpServletResponse response) {

//        已注册邮箱不能重复注册
        if (tokenService.isRegistered(email)){
            log.warn("{} has registered", email);
            return false;
        }

//        验证码是否争取
        boolean validate = codeFeignClient.validate(email, code);

        if (!validate) {
            log.warn("{}[{}],not fit", email, code);
            return false;
        }

        return tokenService.register(email, password, code, response);
    }

//    是否已注册
    @GetMapping("/isRegistered/{email}")
    public Boolean isRegistered(@PathVariable String email) {

        return tokenService.isRegistered(email);
    }

//    登录
    @GetMapping("/login/{email}/{password}")
    public ResponseEntity<String> login(@PathVariable String email,
                                        @PathVariable String password,
                                        HttpServletResponse response) {

        String user = tokenService.login(email, password, response);

        if (user == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }

        return ResponseEntity.ok(user);
    }
}
